<template>
  <div class="app-container" style="height: 100%">
    <div class="app-container-inner user-import">
      <div class="btns_btn">
        <HPlainButton
          @click="downloadExcelTemplate(`/static/file/excel/${routeTitle}模板.xlsx`, routeTitle)"
          >下载模版</HPlainButton
        >
        <div class="dialog-btn">
          <!--工单模块-->
          <el-select
            v-if="routeTitle === '商品资料导入'"
            v-model="goodType"
            style="width: 160px; height: 30px"
            clearable
            placeholder="请选择商品类型"
          >
            <el-option label="成品" :value="1" />
            <el-option label="配件" :value="2" />
          </el-select>

          <!--工单模块-->
          <!-- <el-select
            v-if="routeTitle === '工单资料导入'"
            v-model="orderTypeId"
            :loading="getOrderTypeOptionsLoading"
            :filter-method="handleGetOrderTypeOptions"
            style="width: 160px; height: 30px"
            clearable
            filterable
            placeholder="请选择"
            remote-show-suffix
          >
            <el-option
              v-for="typeItem in orderTypeOptions"
              :key="typeItem.name"
              :disabled="typeItem.select"
              :label="`${typeItem.name}`"
              :value="typeItem.id"
            />
          </el-select> -->

          <!-- 受理客服 -->
          <!-- <el-select
            v-if="routeTitle === '工单资料导入'"
            v-model="customerId"
            :loading="getCustomerOptionsLoading"
            :filter-method="handleGetCustomerOptions"
            style="width: 160px; height: 30px"
            clearable
            filterable
            placeholder="请选择"
            remote-show-suffix
            class="customer_select"
          >
            <el-option :value="0" label="按规则分配">
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>按规则分配</span> <span style="color: #fb9337">系统</span>
              </div>
            </el-option>
            <el-option
              v-for="item in customerOptions"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select> -->
          <HPlainButton :disabled="fileList.length == 0" @click="onConfirmUploadBtnClick"
            >确认上传</HPlainButton
          >
          <HButton @click="onCancelBtnClick">取消</HButton>
        </div>
      </div>
      <el-upload
        class="upload"
        ref="upload"
        accept=".xls, .xlsx"
        v-model:file-list="fileList"
        :auto-upload="false"
        drag
        :limit="1"
        :on-exceed="handleExceed"
        :on-change="handleChange"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text"> 拖动文件到这 或 <em>点击上传</em> </div>
      </el-upload>
      <div style="display: flex" v-if="dataReturned">
        <div style="width: 520px">
          <el-progress
            :stroke-width="15"
            :show-text="false"
            :percentage="Number(dataReturned.currentProgress) || 0"
          />
        </div>
        <div
          style="
            width: 70px;
            color: #303133;
            text-align: center;
            font-size: 16px;
            line-height: 15px;
          "
          >{{ dataReturned.currentProgress }}%</div
        >
      </div>
      <div v-if="dataReturned" class="text_return">
        <p v-html="dataReturned.message" class="red_text"></p>
        <p v-if="dataReturned.end">
          共上传成功
          <span class="tip_num">
            {{ dataReturned.totalCount - dataReturned.importFailtDataList.length }}
          </span>
          条数据
        </p>
        <div v-if="dataReturned && dataReturned.end" style="margin-bottom: 12px">
          <el-divider />
        </div>
        <template v-if="dataReturned.end && dataReturned.importFailtDataList.length > 0">
          <div style="display: flex; justify-content: space-between; align-items: center">
            <span style="font-size: 16px; color: #f56c6c">导入失败的数据</span>
            <el-button
              color="#007cff"
              style="padding: 0 14px; border-radius: 2px; height: 28px"
              type="primary"
              @click="exportToExcel"
              >导出</el-button
            >
          </div>

          <!-- 商品资料导入失败的数据 -->
          <el-table
            border
            class="tableError_list"
            id="el-table"
            stripe
            max-height="220px"
            resizable
            :data="dataReturned.importFailtDataList"
            v-if="routeTitle === '商品资料导入'"
          >
            <el-table-column type="index" label="序号" width="55" fixed />
            <el-table-column
              show-overflow-tooltip
              prop="name"
              label="商品名称"
              min-width="200"
              fixed
            />
            <el-table-column show-overflow-tooltip prop="brand" label="商品品牌" width="150" />
            <el-table-column show-overflow-tooltip prop="model" label="商品型号" width="150" />
            <el-table-column show-overflow-tooltip prop="code" label="商品编号" width="150" />
            <el-table-column show-overflow-tooltip prop="itemNumber" label="商品货号" width="150" />
            <el-table-column show-overflow-tooltip prop="type" label="商品分类" width="150" />
            <el-table-column show-overflow-tooltip prop="unit" label="商品单位" width="150" />
          </el-table>

          <!-- 客户档案导入失败的数据 -->
          <el-table
            border
            class="tableError_list"
            id="el-table"
            stripe
            max-height="220px"
            resizable
            :data="dataReturned.importFailtDataList"
            v-if="routeTitle === '客户档案导入'"
          >
            <el-table-column type="index" label="序号" width="55" fixed />
            <el-table-column show-overflow-tooltip prop="code" label="客户编码" width="130" />
            <el-table-column
              show-overflow-tooltip
              prop="username"
              label="客户联系人姓名"
              width="130"
            />
            <el-table-column show-overflow-tooltip prop="phone" label="联系人手机号" width="130" />
            <el-table-column
              show-overflow-tooltip
              prop="province"
              label="客户地址-省"
              width="130"
            />
            <el-table-column show-overflow-tooltip prop="city" label="客户地址-市" width="130" />
            <el-table-column show-overflow-tooltip prop="area" label="客户地址-县/区" width="130" />
            <el-table-column
              show-overflow-tooltip
              prop="address"
              label="客户详细地址"
              width="130"
            />
            <el-table-column show-overflow-tooltip prop="userType" label="客户分类" width="130" />
            <el-table-column
              show-overflow-tooltip
              prop="selectknowledgeAuthor"
              label="知识库查看权限"
              width="130"
            >
              <template #default="scope">
                <span v-if="scope.row.selectknowledgeAuthor">根据权限查看</span>
                <span v-else>查看所有</span>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="level" label="客户等级" width="130" />
          </el-table>

          <!-- 工程师资料导入失败的数据 -->
          <el-table
            border
            class="tableError_list"
            id="el-table"
            stripe
            max-height="220px"
            resizable
            :data="dataReturned.importFailtDataList"
            v-if="routeTitle === '工程师资料导入'"
          >
            <el-table-column type="index" label="序号" width="55" fixed />
            <el-table-column
              show-overflow-tooltip
              label="工程师姓名"
              prop="username"
              min-width="220"
            />
            <el-table-column
              show-overflow-tooltip
              label="工程师手机号"
              prop="phone"
              min-width="120"
            />
            <el-table-column show-overflow-tooltip prop="superManager" label="管理权限" width="120">
              <template #default="scope">
                {{ scope.row.superManager ? '超级管理员' : '普通管理员' }}
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="工程师等级"
              prop="networkEmpLevel"
              min-width="120"
            />
            <el-table-column
              show-overflow-tooltip
              label="工程师分类"
              prop="networkEmpType"
              min-width="120"
            />
            <el-table-column
              show-overflow-tooltip
              label="所属服务商"
              prop="network"
              min-width="300"
            />
            <el-table-column
              show-overflow-tooltip
              label="工程师技能"
              prop="networkEmpSkill"
              min-width="120"
            />
          </el-table>

          <!-- 工单资料导入失败的数据 -->
          <el-table
            :border="true"
            class="tableError_list"
            id="el-table"
            stripe
            max-height="220px"
            resizable
            :data="dataReturned.importFailtDataList"
            v-if="routeTitle === '工单资料导入'"
          >
            <el-table-column type="index" label="序号" width="55" fixed />
            <el-table-column
              show-overflow-tooltip
              label="导入失败原因"
              prop="excelMsg"
              width="110"
            />
            <el-table-column show-overflow-tooltip label="关联商家" prop="factory" width="110" />
            <el-table-column show-overflow-tooltip label="客户姓名" prop="username" width="110" />
            <el-table-column
              show-overflow-tooltip
              label="客户手机号"
              prop="userPhone"
              width="120"
            />
            <el-table-column show-overflow-tooltip label="客户报单地址" width="300">
              <template #default="scope">
                <span>{{ scope.row.province }}&nbsp;&nbsp;</span>
                <span>{{ scope.row.area }}&nbsp;&nbsp;</span>
                <span>{{ scope.row.city }}&nbsp;</span>
                <span>{{ scope.row.address }}</span>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="商品型号" prop="goodsModel" width="160" />
            <el-table-column show-overflow-tooltip label="商品规格" prop="goodsSpec" width="100" />
            <el-table-column show-overflow-tooltip label="工单状态" prop="status" width="80">
              <template #default="scope">
                <span v-if="scope.row.status === 1">待派单</span>
                <span v-else>已完成</span>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="工单等级" prop="level" width="80" />
            <el-table-column show-overflow-tooltip label="工单类型" prop="module" width="80" />
            <el-table-column show-overflow-tooltip label="服务商" prop="network" width="80" />
            <el-table-column show-overflow-tooltip label="工程师" prop="engineer" width="80" />
            <el-table-column show-overflow-tooltip label="客服" prop="emp" width="80" />
            <el-table-column
              show-overflow-tooltip
              label="工单质保状态"
              prop="overinsured"
              width="100"
            >
              <template #default="scope">
                <span v-if="scope.row.overinsured">保外</span>
                <span v-else>保内</span>
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              label="质保天数"
              prop="warrantyDay"
              width="100"
            />
          </el-table>

          <!-- 服务商资料导入失败的数据 -->
          <el-table
            border
            class="tableError_list"
            id="el-table"
            stripe
            max-height="220px"
            resizable
            :data="dataReturned.importFailtDataList"
            v-if="routeTitle === '服务商资料导入'"
          >
            <el-table-column type="index" label="序号" width="55" fixed />
            <el-table-column
              show-overflow-tooltip
              type="name"
              label="服务商名称"
              width="120"
              fixed
            />
            <el-table-column show-overflow-tooltip label="团队模式" prop="category" width="110">
              <template #default="scope">
                <span v-if="scope.row.teamType === 1">团队</span>
                <span v-else>个人</span>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="服务商模式" prop="category" width="110">
              <template #default="scope">
                <span v-if="scope.row.category === 1">内部服务商</span>
                <span v-else>第三方服务商</span>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="负责人名称" prop="username" width="110" />
            <el-table-column show-overflow-tooltip label="负责人手机号" prop="phone" width="120" />
            <el-table-column
              show-overflow-tooltip
              label="服务商分类"
              prop="networkType"
              width="120"
            />
            <el-table-column show-overflow-tooltip label="服务商地址" width="300">
              <template #default="scope">
                <span>{{ scope.row.province }}&nbsp;&nbsp;</span>
                <span>{{ scope.row.area }}&nbsp;&nbsp;</span>
                <span>{{ scope.row.city }}v&nbsp;</span>
                <span>{{ scope.row.address }}</span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 编码档案导入失败的数据 -->
          <el-table
            border
            class="tableError_list"
            id="el-table"
            stripe
            max-height="220px"
            resizable
            :data="dataReturned.importFailtDataList"
            v-if="routeTitle === '编码档案导入'"
          >
            <el-table-column type="index" label="序号" width="55" fixed />
            <el-table-column prop="type" label="编码类型" width="120" fixed>
              <template #default="scope">
                <span v-if="scope.row.type === 1">成品</span>
                <span v-else>配件</span>
              </template>
            </el-table-column>
            <el-table-column label="编码激活状态" prop="activa" width="110">
              <template #default="scope">
                <span v-if="scope.row.activa">激活</span>
                <span v-else>未激活</span>
              </template>
            </el-table-column>
            <el-table-column label="质保天数" prop="warrantyDay" width="110" />
            <el-table-column label="商品型号" prop="goodsModel" width="110" />
            <el-table-column label="商品规格" prop="goodsSpec" width="110" />
          </el-table>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="goodsExcelImport">
  import { computed, ref, watch } from 'vue'
  import { UploadFilled } from '@element-plus/icons-vue'
  import type { UploadInstance, UploadRawFile, UploadProps } from 'element-plus'
  import { ElMessage, genFileId } from 'element-plus'
  import { initWebSocket } from '@/utils/socket'
  import { downloadExcelTemplate } from '@/utils/download'
  import {
    goodsExcelImport,
    userExcelImport,
    networkEmpImport,
    networkImport,
    codeImport,
    orderImport,
  } from '@/api/upload'
  import moment from 'moment'
  import FileSaver from 'file-saver'
  import * as XLSX from 'xlsx'
  import _ from 'lodash'
  import { useRoute } from 'vue-router'
  import { empPageSelecct } from '@/api/organize'
  import { workModulePageSelect } from '@/api/order'
  import { CustomerOptions, OrderType } from '@/views/order/new/types'
  import { UploadResult } from './types'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.common.import,
  })

  // 激活的路由对象
  const route = useRoute()
  const fileList = ref([]) // 上传的文件
  const upload = ref<UploadInstance>()
  const dataReturned = ref<UploadResult | null>(null)

  /**
   * 取消按钮点击事件
   */
  const onCancelBtnClick = () => {
    fileList.value = []
    dataReturned.value = null
  }

  // 超出限制时执行，覆盖前一个文件
  const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value.handleStart(file)
  }
  const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    onCancelBtnClick()
    fileList.value = uploadFiles
  }

  /**
   * 确认上传按钮点击事件
   */
  const onConfirmUploadBtnClick = _.debounce(() => {
    if (fileList.value.length > 0) {
      // if (route.meta.title === '工单资料导入' && !orderTypeId.value) {
      //   ElMessage({
      //     type: 'warning',
      //     message: '请选择工单模块',
      //   })
      //   return false
      // }

      let uuid = new Date().getTime()
      dataReturned.value = null
      initWebSocket(funProgress, `/ws/progress/${uuid}`)

      if (route.meta.title === '工单资料导入') {
        orderImport(uuid, fileList.value[0].raw).then((res) => {
          if (res) {
            if (!res.data.success) {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: 'error',
                  offset: 200,
                })
            }
          }
        })
      }

      if (route.meta.title == '商品资料导入') {
        goodsExcelImport(fileList.value[0].raw, goodType.value, uuid).then((res) => {
          if (res) {
            if (!res.data.success) {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: 'error',
                  offset: 200,
                })
            }
          }
        })
      } else if (route.meta.title == '客户档案导入') {
        userExcelImport(fileList.value[0].raw, uuid).then((res) => {
          if (res) {
            if (!res.data.success) {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: 'error',
                  offset: 200,
                })
            }
          }
        })
      } else if (route.meta.title == '工程师资料导入') {
        networkEmpImport(fileList.value[0].raw, uuid).then((res) => {
          if (res) {
            if (!res.data.success) {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: 'error',
                  offset: 200,
                })
            }
          }
        })
      } else if (route.meta.title == '服务商资料导入') {
        networkImport(fileList.value[0].raw, uuid).then((res) => {
          if (res) {
            if (!res.data.success) {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: 'error',
                  offset: 200,
                })
            }
          }
        })
      } else if (route.meta.title === '编码档案导入') {
        codeImport(fileList.value[0].raw, uuid).then((res) => {
          if (res) {
            if (!res.data.success) {
              if (res.data.isError)
                ElMessage({
                  showClose: true,
                  message: res.data.message,
                  type: 'error',
                  offset: 200,
                })
            }
          }
        })
      }
    }
  }, 600)

  /**
   * 获取WebSocket返回的数据
   * @param {object} msg - WebSocket返回的数据
   */
  const funProgress = (msg: UploadResult) => {
    dataReturned.value = msg
    if (Number(dataReturned.value.currentProgress) >= 100) {
      dataReturned.value.currentProgress = '100'
    }
    msg.end
  }

  // 准备要导出的数据   https://blog.csdn.net/qq_40036754/article/details/117228315
  const exportToExcel = _.debounce(() => {
    // const worksheet = XLSX.utils.json_to_sheet(data);
    // const workbook = XLSX.utils.book_new();
    // XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    // XLSX.writeFile(workbook, `上传失败数据_${moment(new Date()).format('YYYYMMDD')}.xlsx`);
    const wb = XLSX.utils.table_to_book(document.querySelector('#el-table'))
    const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
    try {
      FileSaver.saveAs(
        new Blob([wbout], { type: 'application/octet-stream' }),
        `上传失败数据_${moment(new Date()).format('YYYYMMDD')}.xlsx`,
      )
    } catch (e) {
      if (typeof console !== 'undefined') {
        // 保存失败
      }
    }
  }, 600)

  // 商品类型
  const goodType = ref(1)

  // 工单分类id
  const orderTypeId = ref('')

  // 获取工单类型下拉选项请求参数
  const getOrderTypeOptionsKeyword = ref('')

  // 工单模块下拉选项
  const orderTypeOptions = ref<Array<OrderType>>([])

  // 获取工单分类下拉选项加载
  const getOrderTypeOptionsLoading = ref(false)

  /**
   * 获取工单类型下拉选项
   */
  const handleGetOrderTypeOptions = _.throttle((query: string) => {
    if (query === getOrderTypeOptionsKeyword.value) {
      return false
    }
    getOrderTypeOptionsKeyword.value = query
    getOrderTypeOptionsFn(getOrderTypeOptionsKeyword.value)
  }, 500)

  /**
   * 获取工单类型下拉选项方法
   */
  const getOrderTypeOptionsFn = async (query: string) => {
    getOrderTypeOptionsLoading.value = true
    const data = {
      name: query,
      page: 0,
      limit: 0,
    }
    const res = await workModulePageSelect(data)
    if (res.data.success) {
      orderTypeOptions.value = res.data.data.rows
    }
    getOrderTypeOptionsLoading.value = false
  }

  // 获取工单客户组下拉选项加载
  const getCustomerOptionsLoading = ref(false)

  // 工单客服组下拉选项
  const customerOptions = ref<Array<CustomerOptions>>([])

  // 选中的工单客服
  const customerId = ref(0)

  // 获取工单客服组下拉选项关键字
  const getCustomerKeyword = ref('')

  /**
   * 工单客服组下拉列表查询
   */
  const handleGetCustomerOptions = _.throttle((val: string) => {
    if (getCustomerKeyword.value !== val) {
      getCustomerKeyword.value = val
      getCustomerOptionsFn(getCustomerKeyword.value)
    }
  }, 500)

  /**
   * 获取工单客服组下拉选项方法
   * @param {string} query - 查询关键字
   */
  const getCustomerOptionsFn = async (query: string) => {
    const data = {
      limit: 0,
      name: query,
      page: 0,
    }
    getCustomerOptionsLoading.value = true
    const res = await empPageSelecct(data)
    if (res.data.success) {
      customerOptions.value = res.data.data.rows
    }
    getCustomerOptionsLoading.value = false
  }

  const routeTitle = computed(() => route.meta.title as string)

  watch(
    () => route,
    (value) => {
      if (value.name === 'orderExcelImport' && value.meta.title === '工单资料导入') {
        getCustomerOptionsFn('')
        getOrderTypeOptionsFn('')
      }
      if (value.name === 'goodsExcelImport' && value.meta.title === '商品资料导入') {
        goodType.value = Number(route.query.type)
      }
    },
    { immediate: true, deep: true },
  )
</script>

<style scoped lang="scss">
  :deep(.el-upload-dragger) {
    padding: 20px 10px;
  }
  .user-import {
    display: flex;
    flex-direction: column;
    flex: 1;

    .btns_btn {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .dialog-btn {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        gap: 5px;

        :deep(.el-select__wrapper) {
          height: 30px;
        }

        .confirm_upload_btn {
          background-color: $primaryColor;
          border-color: $primaryColor;
          color: #fff;

          &:hover {
            background-color: rgba($primaryColor, 0.8);
            border-color: rgba($primaryColor, 0.8);
          }
        }
      }
    }

    .text_return {
      margin: 0 12px 16px;

      p {
        margin: 8px 0;

        .tip_num {
          color: #007cff;
          font-size: 14px;
          padding: 0 4px;
          font-weight: bold;
        }

        &.red_text {
          max-height: 200px;
          overflow: auto;
          color: #f56c6c;
        }
      }

      .tableError_list {
        margin-top: 12px;
      }

      .export_error {
        display: flex;
        justify-content: end;
        align-items: center;

        .btn-w {
          width: 70px;
        }
      }
    }
  }
</style>
